package cn.wen.yinxiu.member.server.socket.handler;

import cn.wen.yinxiu.common.toolkit.SocketChannelUtil;
import cn.wen.yinxiu.member.builder.BeanBuilderAssistant;
import cn.wen.yinxiu.member.server.protocol.Command;
import cn.wen.yinxiu.member.server.protocol.msg.MsgGroupResponse;
import cn.wen.yinxiu.member.server.protocol.msg.MsgRequest;
import cn.wen.yinxiu.member.server.protocol.msg.MsgResponse;
import cn.wen.yinxiu.member.service.UsersService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.nio.charset.Charset;
import java.util.Date;

import static cn.wen.yinxiu.common.constant.Constant.TalkType.Friend;
import static cn.wen.yinxiu.common.constant.Constant.TalkType.Group;

/**
 * @ClassName: MsgHandler
 * @Author: 小飞
 * @Date: 2023/5/28 14:34
 * @Description: 消息信息处理
 */
@Slf4j
public class MsgHandler extends SimpleChannelInboundHandler<MsgRequest> {

    private final UsersService userService;

    public MsgHandler(UsersService userService) {
        this.userService = userService;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MsgRequest msg) throws Exception {
        log.info("消息信息处理：{}", JSON.toJSONString(msg));
        msg.setMsgTime(new Date());
        // 异步写库
        userService.asyncAppendChatRecord(BeanBuilderAssistant.buildChatRecordInfo(msg));
        // 添加对话框[如果对方没有你的对话框则添加]
        userService.addTalkBoxInfo(msg.getFriendId(), msg.getUserId(), Friend.getCode());
        // 获取好友通信管道
        Channel friendChannel = SocketChannelUtil.getChannel(msg.getFriendId());
        if (null == friendChannel) {
            return;
        }
        // 发送消息
        MsgResponse msgResponse = new MsgResponse();
        msgResponse.setFriendId(msg.getUserId());
        msgResponse.setMsgText(msg.getMsgText());
        msgResponse.setMsgTime(msg.getMsgTime());
        msgResponse.setMsgType(msg.getMsgType());
        // 响应数据
        friendChannel.writeAndFlush(new TextWebSocketFrame(getByteBuf(channelHandlerContext, msg.getFriendId(), msgResponse)));
    }

    public ByteBuf getByteBuf(ChannelHandlerContext ctx, Long userId, MsgResponse msgResponse) {
        ByteBuf bytebuf = ctx.alloc().buffer();
        JSONObject data = new JSONObject();
        data.put("type", Command.MsgResponse);
        data.put("code", 200);
        JSONObject params = new JSONObject();
        params.put("userId", userId);
        params.put("msgInfo", msgResponse);
        data.put("data", params);
        byte []bytes = data.toJSONString().getBytes(Charset.forName("utf-8"));
        bytebuf.writeBytes(bytes);
        return bytebuf;
    }
}
